<template>
  <div class="mobile-nav sticky top-0 left-0 z-10 dark:bg-zinc-800">
    <ul
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 dark:text-zinc-50 overflow-hidden shadow-l-white"
      ref="ulRef"
    >
      <li
        v-for="{ id, name } in props.categorys"
        :key="id"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200"
        :class="{
          'text-zinc-100 ': currentCategoryId === id,
          'dark:text-zinc-900': currentCategoryId === id
        }"
        @click="setStoreCurrentCategoryId(id)"
        :ref="setRef"
      >
        {{ name }}
      </li>
      <li class="shrink-0 px-1.5 py-0.5 z-10 duration-200"></li>
      <li
        class="shrink-0 px-1.5 py-0.5 duration-200 fixed right-0 z-20 bg-white"
        @click="isOpenPopup = true"
      >
        <svg-icon class="w-1.5 h-1.5" name="hamburger"></svg-icon>
      </li>
      <!-- 滑块 -->
      <li
        class="absolute h-nav-height bg-zinc-900 dark:bg-zinc-50 rounded-lg duration-200"
        :style="sliderStyle"
      ></li>
    </ul>
    <pop-up v-model:modelValue="isOpenPopup">
      <div @click="changTheme(THEME_LIGHT)">白色</div>
      <div @click="changTheme(THEME_DARK)">黑色</div>
      <div @click="changTheme(THEME_SYSTEM)">跟随系统</div>
    </pop-up>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUpdate } from 'vue'
import { storeToRefs } from 'pinia'
import { useScroll } from '@vueuse/core'
import { useCurrentCategory } from '@/stores/currentCategory'
import { THEME_DARK, THEME_LIGHT, THEME_SYSTEM } from '@/constants'
import { useThemeStore } from '@/stores/theme'
const { setCurrentCategoryId } = useCurrentCategory()
const { currentCategoryId } = storeToRefs(useCurrentCategory())
const props = defineProps({
  categorys: {
    type: Array,
    default: () => {}
  }
})
const ulRef = ref()
const { x: ulScrollLeft } = useScroll(ulRef)
let itemRefs = []
const setRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}
onBeforeUpdate(() => {
  // console.log('onBeforeUpdate')
  itemRefs = []
})
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '1.25rem'
})

watch(
  () => currentCategoryId.value,
  (newVal) => {
    const index = props.categorys.findIndex((itr) => itr.id === newVal)
    const { left, width } = itemRefs[index].getBoundingClientRect()
    sliderStyle.value = {
      transform: `translateX(${ulScrollLeft.value + left - 10 + 'px'})`,
      width: width + 'px'
    }
  }
)

const setStoreCurrentCategoryId = (id) => {
  setCurrentCategoryId(id)
}

const isOpenPopup = ref(false)

const { setTheme } = useThemeStore()
const changTheme = (theme) => {
  setTheme(theme)
}
</script>

<style lang="scss" scoped>
.mobile-nav {
  height: 1.1rem;
  ul {
    height: 100%;
  }
}
</style>
